package cn.fetosoft.woodpecker.core.data.service.impl;

import cn.fetosoft.woodpecker.core.data.base.AbstractMongoService;
import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.form.ElementForm;
import cn.fetosoft.woodpecker.core.data.service.ElementService;
import cn.fetosoft.woodpecker.core.enums.ElementCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/6/11 9:07
 */
@Slf4j
@Service
public class ElementServiceImpl<T extends BaseElement> extends AbstractMongoService<T, ElementForm>
		implements ElementService<T> {

	@Override
	public int findMaxSort(String planId, String parentId, Class<T> clazz) {
		int maxSort = 1;
		ElementForm form = new ElementForm();
		form.setPlanId(planId);
		form.setParentId(parentId);
		form.setDescField("sort");
		form.setRows(1);
		try {
			List<T> list = this.selectListByForm(form, clazz);
			if(!CollectionUtils.isEmpty(list)){
				T t = list.get(0);
				maxSort = t.getSort() + 1;
			}
		} catch (Exception e) {
			log.error("findByElementId", e);
		}
		return maxSort;
	}

	@Override
	public Map<String, T> findElements(Class<T> clazz) {
		Map<String, T> map = new HashMap<>();
		ElementForm form = new ElementForm();
		form.setCategory(ElementCategory.TEST_PLAN.getName());
		form.setRows(0);
		try {
			List<T> list = this.selectListByForm(form, clazz);
			if(!CollectionUtils.isEmpty(list)){
				for(T t : list){
					map.put(t.getId(), t);
				}
			}
		} catch (Exception e) {
			log.error("findElements", e);
		}
		return map;
	}
}
